import logging
from datetime import datetime
import pandas as pd


def log_duplicates_to_file(df, log_file="log/duplicates.log"):
    """
    修复后的日志记录函数，支持Unicode字符
    """
    # 配置UTF-8编码的日志
    logging.basicConfig(
        handlers=[logging.FileHandler(log_file, encoding='utf-8')],
        level=logging.ERROR,
        format='%(asctime)s | %(levelname)s | %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S'
    )

    # 检测重复值
    dup_mask = df.index.duplicated(keep=False)
    if not dup_mask.any():
        return True

    # 生成日志内容
    dup_stats = (df.index[dup_mask]
                 .value_counts()
                 .reset_index()
                 .rename(columns={'index': '重复值', 'count': '出现次数'}))

    error_msg = [
        "\n" + "=" * 60,
        f"❌ 第一列重复值检测（当前时间：{datetime.now().strftime('%Y-%m-%d  %H:%M:%S')}）",
        f"共发现 {len(dup_stats)} 种重复值，总计 {dup_mask.sum()}  处",
        "-" * 60,
        dup_stats.to_string(index=False, justify='center'),
        "=" * 60
    ]

    # logging.error(error_msg)
    # 逐行写入日志（确保换行符生效）
    for line in error_msg:
        logging.error(line)

    return False